package com.rzjm.api.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 *@Author: ZhouWei
 *@Description:  调查问卷相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/citizen")//url:模块/资源/{}/细分
public class CitizenController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SurveyService surveyService;
    @Resource
    private SurveyQuestionService questionService;
    @Resource
    private SurveyUserRecordService surveyUserRecordService;
    @Resource
    private CitizenService citizenService;
    @Resource
    private SysUserTownRelationService townRelationService;
    @Resource
    private TownsService townsService;

    @Resource
    private SysUserService sysUserService;
    /**
     * 居民详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "citizen/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("citizen/detail 接收的参数： "+requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int roomId = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            System.out.println(user.getNickName() + "绑定的 sys_user_id = " + user.getSysUserId());

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            Towns towns = townsService.findById(sysUser.getTownId());
            if(towns == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该乡镇不存在"),true,true);
            }

            if(towns.getIsControl() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂停服务"),true,true);
            }

            Citizen citizen = citizenService.findById(roomId);
            if(citizen == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该居民信息不存在"),true,true);
            }

            if(sysUser.getUserLevel() == 2){//镇级
                if(sysUser.getTownId().intValue() != citizen.getTownId().intValue()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该住户上报权限"),true,true);
                }
            } else if(sysUser.getUserLevel() == 3){//村级
                QueryWrapper<SysUserTownRelation> qw = new QueryWrapper<>();
                qw.eq("town_id",citizen.getTownId());
                qw.eq("village_id",citizen.getVillageId());
                qw.eq("sys_user_id",sysUser.getUserId());
//                qw.eq("state",1);
                qw.last("limit 1");
                SysUserTownRelation townRelation = townRelationService.getOne(qw);
                if(townRelation == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该住户上报权限"),true,true);
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",citizen),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            List<Survey> surveys = surveyService.selectListByColumn("state",0);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",surveys.size(),surveys),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


}
